﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using QBZ.Evaluation.Domains;
using QBZ.Evaluation.Domains.Permissions;
using QBZ.Evaluation.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QBZ.Evaluation.Apis.Controllers
{
    //[EnableCors("AllowAll")]
    [Route("api/[controller]/[action]/{id?}")]
    [ApiController]
    [Authorize]
    public class UserController : Controller
    {
        private readonly UserDomain _user;
        private readonly ILogger<UserController> _logger;
        private readonly RoleDomain _role;

        public UserController(UserDomain user, RoleDomain role, ILogger<UserController> logger)
        {
            _user = user;
            _logger = logger;
            _role = role;
        }

        
        [HttpGet]
        [PermissionFilter(UserLevel.RegUser)]

        public ActionResult<List<UserModel>> Index()
        {
            return _user.GetAll();
        }

        [HttpGet, HttpPost]
        //[AllowAnonymous]
        [PermissionFilter(UserLevel.SuperAdmin)]
        public ActionResult<int> AddUser([FromForm] UserModel user)
        {
            return _user.AddUser(user);
        }


        [HttpPost]
        [AllowAnonymous]
        public ActionResult<ResponseModel> Login([FromForm]LoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                return _user.Login(model, HttpContext);
            }
            else
            {
                var res = new ResponseModel(ErrReason.WrongDataFormat);
                res.status.msg += ":" + ModelState.FirstOrDefault();
                return res;
            }
        }

        [HttpPost]
        [PermissionFilter(UserLevel.RegUser)]
        public IActionResult MergeAccount([FromForm]LoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                var userId = 0;
                object userLevel = UserLevel.RegUser;
                if (HttpContext.User.Identity.IsAuthenticated)
                {
                    int.TryParse(HttpContext.User.FindFirst(_ => _.Type == "UserId").Value, out userId);
                    if (!Enum.TryParse(typeof(UserLevel), HttpContext.User.FindFirst(_ => _.Type == "UserLevel").Value, out userLevel))
                    {
                        userLevel = UserLevel.NoLogin;
                    }
                }
                return Json(_user.MargeAccount(model, userId, (UserLevel)userLevel));
            }
            else
            {
                var res = new ResponseModel(ErrReason.WrongDataFormat);
                res.status.msg += ":" + ModelState.FirstOrDefault();
                return Json(res);
            }
        }

        [HttpGet, HttpPost]
        [PermissionFilter(UserLevel.SuperAdmin)]
        public ActionResult<ResponseModel> Infos([FromForm]BsTableRequsetModel model)
        {
            var res = new ResponseModel(ErrReason.Ok);
            if (string.IsNullOrWhiteSpace(model.sort))
            {
                model.sort = "UserId";
            }
            if (string.IsNullOrWhiteSpace(model.multiSort))
            {
                model.multiSort = "[{\"sortName\":\"" + model.sort + "\",\"sortOrder\":\"" + model.order + "\"}]";
            }
            res.result = _user.getUsersInfo(model.filter, model.multiSort, model.offset, model.limit);
            return res;
        }



        [HttpGet, HttpPost]
        [PermissionFilter(UserLevel.RegUser)]
        public ActionResult<ResponseModel> Info()
        {
            var res = new ResponseModel();
            var result = new UserInfo();
            var userIdClaim = HttpContext.User.FindFirst(_ => _.Type == "UserId");
            if (userIdClaim != null)
            {
                var userId = int.Parse(userIdClaim.Value);
                var user = _user.FindUser(userId);
                if (user == null)
                {
                    res.status = new ResponseStatusModel(ErrReason.UserNotExist);
                }
                else
                {
                    result.BaseInfo = user;
                    result.Menu = _user.GetMenus((UserLevel)result.BaseInfo.UserLevel);
                    result.Role = _role.GetAll();
                    res.result = result;
                    res.status = new ResponseStatusModel(ErrReason.Ok);
                }
            }
            else
            {
                res.status = new ResponseStatusModel(ErrReason.AccessDenied);
            }
            return res;
        }

        [HttpPost]
        [PermissionFilter(UserLevel.SuperAdmin)]
        public ActionResult<ResponseModel> ResetPassword([FromForm]int userId)
        {
            _user.ResetPassword(userId);
            return new ResponseModel(ErrReason.Ok);
        }

        [HttpPost]
        [PermissionFilter(UserLevel.SuperAdmin)]
        public ActionResult<ResponseModel> SetUserLevel([FromForm]SetUserLevelModel setUserLevel)
        {
            _user.SetUserLevel(new UserBaseModel { UserId = setUserLevel.UserId, UserLevel = Enum.Parse<UserLevel>(setUserLevel.UserLevel) });
            return new ResponseModel(ErrReason.Ok);
        }

    }
}